<%args>
	$dbh
	$auth
	$id => undef
</%args>
<%init>
use Data::Dumper;
use POSIX;
use locale;
#setlocale(&LC_COLLATE, 'ru_RU.KOI8-R');
use utf8;

if($auth->{gid} ne '1' && $auth->{gid} ne '2') {	# только admin и manager
	$r->status_line('');
	$m->clear_buffer;
	$m->abort(404);
}

map { $_ =~ s/\D//g; } ($id, $ARGS{id}, $ARGS{gid});
map { $_ = 0 if($_ > 1000) } ( $id, $ARGS{id}, $ARGS{gid});

$id ||= $ARGS{id};

my %Gr;
my ($List, $Usr, $sth);
my %Err;
my $OK=0;

if($ARGS{cancel}) {
	map {undef $_;} $ARGS{id},$id,$ARGS{submit},$ARGS{"add_new"};
}

$sth = $dbh->prepare("SELECT id,name FROM groups");
$sth->execute();
while(my $r = $sth->fetchrow_hashref) {
	$Gr{$r->{id}} = $r->{name};
}
$sth->finish;

if($ARGS{submit}) {	# сохраняем запись
	if($ARGS{delete} && $id) {
		$dbh->do("DELETE FROM auth WHERE id=$id");
		undef $id;
	} else {

		map {s/\'/\&quot;/g;} ($ARGS{name},$ARGS{login},$ARGS{memo});
		$ARGS{login} =~ s/\W//g;
		$Err{login}++	unless($ARGS{login});
		# проверить уникальность если добавление
		unless($id) {
			$sth = $dbh->prepare("SELECT id FROM auth WHERE login=?");
			$sth->execute($ARGS{login});
			my ($exist) = $sth->fetch;
			$sth->finish;
			$Err{login}++	if($exist);
		}

		$Err{gid}++	unless($ARGS{gid});
		$Err{gid}++	unless(exists $Gr{$ARGS{gid}});
		$ARGS{email} =~ s/[^\w\.\@\-]//g;
		$Err{password}++	if(length($ARGS{password}) > 50);
		$Err{password}++	if(!$ARGS{password} && !$id);	# для новой записи пароль необходим

		my @saltair = ('A'..'Z', 'a'..'z', '0'..'9');
		my $salt = join("", @saltair[map{rand @saltair} (1..8)]);
		my $cpass = crypt($ARGS{password},"\$1\$$salt\$");
	
		my $active = 0;
		$active = 1	if($ARGS{active} =~ /on/i);

		unless(%Err) {
			if($id) {	# обновляем запись
				if($ARGS{password}) {
					$sth = $dbh->prepare("UPDATE auth set name=?,login=?,password=?,gid=?,email=?,active=?,memo=?,modtime=now() WHERE id=?");
					$sth->execute($ARGS{name} || '',$ARGS{login},$cpass,$ARGS{gid},$ARGS{email} || '',$active,$ARGS{memo} || '',$id);
				} else {	# пароль решили не менять
					$sth = $dbh->prepare("UPDATE auth set name=?,login=?,gid=?,email=?,active=?,memo=?,modtime=now() WHERE id=?");
					$sth->execute($ARGS{name} || '',$ARGS{login},$ARGS{gid},$ARGS{email} || '',$active,$ARGS{memo} || '',$id);
				}
				undef $id;

			} else {	# новая запись
				$sth = $dbh->prepare("INSERT INTO auth (name,login,password,gid,email,active,memo) VALUES (?,?,?,?,?,?,?)");
				$sth->execute($ARGS{name} || '',$ARGS{login},$cpass,$ARGS{gid},$ARGS{email} || '',$active,$ARGS{memo} || '');
				undef $ARGS{"add_new"};
			}
		}
	}
}

if($id) {
	$sth = $dbh->prepare("select A.id,A.name,A.login,A.email,A.modtime,A.gid,G.name AS group,A.password,A.memo,A.active from auth A
		inner join groups G on A.gid = G.id WHERE A.id=? LIMIT 1");
	$sth->execute($id);
	($Usr) = ($sth->fetchrow_hashref);


} else {	# Полный список
	$sth = $dbh->prepare("select A.id,A.name,A.login,A.email,A.modtime,A.gid,G.name AS group,A.active from auth A
		inner join groups G on A.gid = G.id ORDER BY A.name,A.login");

	$sth->execute();
	while(my $r = $sth->fetchrow_hashref) {
		push @{$List}, $r;
	}
	$sth->finish;
}

</%init>
<p><a href="auth.html?add_new=1">Добавить</a></p>
%if($id || $ARGS{"add_new"}) {
<form action="auth.html" method="POST">
<input type="hidden" name="add_new" value="<%$ARGS{"add_new"}%>">
<input type="hidden" name="id" value="<%$ARGS{id}%>">
<table border="1">
<tr>
<td align="right">Пользователь:</td>
<td><input type="text" name="name" value="<%$ARGS{name} || $Usr->{name}%>"></td>
</tr><tr>
% my $mark = $Err{login} ? 'style=color:red' : '';
<td align="right"><div <% $mark%>>Логин:</div></td>
<td><input type="text" name="login" value="<%$ARGS{login} || $Usr->{login}%>"></td>
</tr><tr>
% $mark = $Err{password} ? 'style=color:red' : '';
<td align="right"><div <% $mark%>>Пароль:</div></td>
<td><input type="text" name="password" value=""></td>
</tr><tr>
% $mark = $Err{gid} ? 'style=color:red' : '';
<td align="right"><div <% $mark%>>Группа доступа:</div></td>
<td>
<select name="gid">
<option></option>
%foreach(sort {$a <=> $b} keys %Gr) {
<option value="<%$_%>" <% ((!$ARGS{submit} ? $Usr->{gid} : $ARGS{gid}) eq $_)? "selected":"" %>><%$Gr{$_}%></option>
%}
</select>
</td>
</tr><tr>
<td align="right">Активен:</td>
<td><input type="checkbox" name="active" <% $ARGS{active} || (!$ARGS{submit} ? $Usr->{active} : "") ? "checked":"" %>></td>
</tr><tr>
<td align="right">Почта:</td>
<td><input type="text" name="email" value="<%$ARGS{email} || $Usr->{email}%>"></td>
</tr><tr>
<td align="right">Комментарий:</td>
<td><textarea name="memo" cols="30" rows="2"><%$ARGS{memo} || (!$ARGS{submit} ? $Usr->{memo} : "")%></textarea></td>
</tr>
<tr>
<td><input type="submit" name="cancel" value="Отменить"></td>
<td><input type="submit" name="submit" value="Сохранить">&nbsp;
%unless($ARGS{"add_new"}) {
<i>удалить</i><input type="checkbox" name="delete">
%}
</td>
</tr>






</table>
</form>
%} else {

%my $n = 1;
<table border="1">
<tr>
<td align="center">N</td>
<td align="center">Логин</td>
<td align="center">Группа</td>
<td align="center">Имя</td>
<td align="center">Почта</td>
</tr>
%foreach my $rec (@{$List}) {
<tr>
%my $mark = $rec->{active} ? '':'style=color:red';
<td <%$mark%>><%$n%>.</td>
<td><a href="?id=<%$rec->{id}%>"><%$rec->{login}%></a></td>
<td><%$rec->{group}%></td>
<td><%$rec->{name}%></td>
<td><%$rec->{email}%></td>
</tr>
%	$n++;
%}
</table>
%}
